module Skit
  module Statsd
    class Client
      extend Forwardable

      METHODS = %i(increment decrement count gauge set timing time batch)

      def initialize(host, port, namespace, environment)
        @host = host
        @port = port
        @namespace = namespace

        define_methods_for(environment)
      end

      def define_methods_for(environment)
        if environment.to_s == 'production'
          singleton_class.class_eval { def_delegators :client, *METHODS }
        else
          # use empty methods in non-production environment
          singleton_class.class_eval do
            METHODS.each do |method|
              define_method method, ->(*args, &block) { block.call if block }
            end
          end
        end
      end

      def timing_from(stat, start, sample_rate = 1)
        timing(stat, ((Time.now.to_f - start.to_f) * 1000).round, sample_rate)
      end

      private

      def client
        @statsd ||= ::Statsd.new(@host, @port).tap do |sd|
          sd.namespace = @namespace
        end
      end
    end
  end
end
